from rest_framework import serializers
from home.models import NavCategory, CourseCategory, Banner


class NavCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = NavCategory
        fields = ['id', 'name', 'display_name', 'weight', 'external_link']


class SimpleCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseCategory
        fields = ['id', 'name', 'level', 'description']


class ChildCategorySerializer(serializers.ModelSerializer):
    """用于第三级分类的序列化器"""
    class Meta:
        model = CourseCategory
        fields = ['id', 'name', 'level', 'description']


class SubCategorySerializer(serializers.ModelSerializer):
    """用于第二级分类的序列化器"""
    children = serializers.SerializerMethodField()

    class Meta:
        model = CourseCategory
        fields = ['id', 'name', 'level', 'description', 'children']

    def get_children(self, obj):
        children = CourseCategory.objects.filter(
            parent=obj,
            is_show=True,
            is_delete=False
        ).order_by('level')

        if children:
            ser = ChildCategorySerializer(children, many=True)
            return ser.data
        return []


class CourseCategorySerializer(serializers.ModelSerializer):
    """用于第一级分类的序列化器"""
    children = serializers.SerializerMethodField()

    class Meta:
        model = CourseCategory
        fields = ['id', 'name', 'level', 'description', 'children']

    def get_children(self, obj):
        children = CourseCategory.objects.filter(
            parent=obj,
            is_show=True,
            is_delete=False
        ).order_by('level')

        if children:
            ser = SubCategorySerializer(children, many=True)
            return ser.data
        return []
class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = ['id', 'image', 'link', 'is_show', 'is_delete']